package com.multiThread;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class FutrueTaskTest {

    // 线程池
    private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, 3, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5));

    // 要执行的任务
    private class MyTask implements Callable {
        CountDownLatch cdl;

        public MyTask(CountDownLatch cdl) {
            this.cdl = cdl;
        }

        @Override
        public Object call() throws Exception {
            try {
                // 模拟业务
                Thread.sleep(3000);
                // 模拟返回查询结查
                int queryResult = new Random().nextInt(10);
                System.out.println(queryResult);
                // 模拟异常
//                if (queryResult > 7) {
//                    int i = 0;
//                    int j = 10 / i;
//                }
                return queryResult;
            } finally {
                cdl.countDown();
            }
        }
    }

    // 处理多任务方法
    public String processMuiltiTask() {
        // 返回结果
        Integer result = 0;
        int threadNum = 5;
        CountDownLatch cdl = new CountDownLatch(threadNum);
        List<FutureTask> taskList = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            FutureTask<MyTask> task = new FutureTask(new MyTask(cdl));
            taskList.add(task);
            threadPool.submit(task);
        }
        try {
            System.out.println("调用await方法了");
            long startTime = System.currentTimeMillis();
            cdl.await();
            long endTime = System.currentTimeMillis();
            for (FutureTask task : taskList) {
                try {
                    String r = task.get().toString();
                    result += Integer.parseInt(task.get().toString());
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("总耗时：" + ((endTime - startTime) / 1000));
            System.out.println("执行结果：" + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 线上是不会关掉的
            threadPool.shutdown();
        }


        return null;
    }

    public static void main(String[] args) {
        new FutrueTaskTest().processMuiltiTask();
    }
}
